"use strict"
const fetch = require('node-fetch')
const cheerio = require('cheerio')

const e = raw => raw.replace(/([\\'"])/gm, '\\$1')
const e_url = raw => raw//.replace(/(https:\/\/)/gm, 'http://')
const opt = {
    timeout : 5000,
}

module.exports = [
    function *() {
        const url = 'http://www.panda.tv/live_lists'
        const limit = 120
        let page = 0
        let page_count = 0

        const format = (data) => {
            if(page_count  === 0) {
                page_count = Math.ceil(data.data.total/limit)
            }
            return data.data.items.map( i => ({
                live_id : 1,
                room_name : e(i.name),
                id : 'p_' + i.userinfo.rid,
                room_id :i.id,
                name : e(i.userinfo.nickName),
                online : i.person_num,
                cover : e_url(i.pictures.img),
                avatar : e_url(i.userinfo.avatar),
                url : `http://www.panda.tv/${i.id}`,
                category_name : i.classification.cname,
                category_url : "http://www.panda.tv/cate/" + i.classification.ename,
                category_id : i.classification.ename,
            }))
        }

        while(1) {
            if (page_count && page > page_count) return

            yield fetch(`${url}?pageno=${++page}&pagenum=${limit}&order=person_num&status=2`, opt)
                .then(_=>_.json())
                .then(format)
        }
    },

    function* () {
        const url = 'http://open.douyucdn.cn/api/RoomApi/live'
        const limit = 100
        let page = 0
        let done = false

        const format = result => {
            const data = result.data
            if (data.length === 0) return done = true
            
            return data.map( i => ({
                live_id : 2,
                name : e(i.nickname),
                room_name : e(i.room_name),
                room_id : i.room_id,
                online : i.online,
                id : 'd_' + i.owner_uid,
                url : i.url,
                cover : e_url(i.room_src),
                avatar : e_url(i.avatar),
                category_id : i.cate_id,
                category_name : i.game_name,
                category_url : i.game_url,
            }))
        }

        while (!done)
            yield fetch(`${url}?offset=${page++*100}&limit=${limit}`, opt)
            .then(_=>_.json())
            .then(format)
    },

    function *() {
        const url = 'http://www.quanmin.tv/json/play/list'
        let page = 0
        let page_count = 0

        const format = result => {
            if (page_count === 0) page_count = result.pageCount
            
            return result.data.map( i => ({
                live_id : 3,
                name : e(i.nick),
                room_name : e(i.title),
                room_id : i.uid,
                online : i.view,
                id : 'q_' + i.uid,
                url : `http://www.quanmin.tv/v/${i.slug ? i.slug : i.uid}`,
                cover : e_url(i.thumb),
                avatar : e_url(i.avatar),
                category_id : i.category_id,
                category_name : i.category_name,
                category_url : `http://www.quanmin.tv/game/${i.category_slug}`,
                intro : i.intro
            }))
        }

        while (!page_count || page < page_count) {
            yield fetch(`${url}${page++ ? `_${page}` : ''}.json`, opt)
            .then(_=>_.json())
            .then(format)
        }
    },

    function *(){
        // 战旗TV url格式：http://www.zhanqi.tv/api/static/v2.1/live/list/{$limit}/{$page}.json
        //https://apis.zhanqi.tv/static/v2.1/room/154601.json
        const url = "http://www.zhanqi.tv/api/static/v2.1/live/list"
        const limit = 100
        let page = 1
        let page_count = 0


        const format = result => {
            if (page_count === 0) page_count = Math.ceil(result.data.cnt / limit)

            return result.data.rooms.map(i => ({
                live_id : 4,
                name : e(i.nickname),
                room_name : e(i.title),
                room_id : i.id,
                online : i.online,
                id : 'zhanqi_' + i.uid,
                url : `${url}${i.url}`,
                cover : e_url(i.bpic),
                avatar : e_url(i.avatar) + '-big',
                category_id : i.gameId,
                category_name : i.gameName,
                category_url : `${url}${i.gameUrl}`,
                sex : i.gender
            }))
        }

        while (!page_count || page < page_count) {
            yield fetch(`${url}/${limit}/${page++}.json`, opt)
            .then(_=>_.json())
            .then(format)
        }

    },

    function *() {
        //龙珠TV url格式：http://api.plu.cn/tga/streams?max-results=${limit}&start-index=${offset}&sort-by=views&game=0
        // max_limit = 50

        const url = "http://api.plu.cn/tga/streams?sort-by=views&game=0"
        const limit = 50
        let page = 0
        let page_count = 0

        const format = result => {
            if (page_count === 0) page_count = Math.ceil(result.data.totalItems / limit)

            return result.data.items.map( i=> ({
                live_id : 5,
                name : e(i.channel.name),
                room_name : e(i.channel.status),
                room_id : i.channel.id,
                online : i.viewers,
                id : 'longzhu_' + i.channel.id,
                url : i.channel.url,
                cover : e_url(i.preview),
                avatar : e_url(i.channel.avatar),
                category_id : i.game[0].id,
                category_name : i.game[0].name,
                category_url : `http://longzhu.com/channels/${i.game[0].tag}`,
            }))
        }

         while (!page_count || page < page_count) {
            yield fetch(`${url}&max-results=${limit}&start-index=${page++*limit}`, opt)
            .then(_=>_.json())
            .then(format)
        }
    },

    function *() {
        //虎牙TV url格式：http://www.huya.com/cache.php?m=Live&do=ajaxAllLiveByPage&page=${page}
        //虎牙只能一次获取20条数据, 只抓取前1000条数据
        const url = "http://www.huya.com/cache.php?m=Live&do=ajaxAllLiveByPage&page="
        const page_count = 51
        let page = 1

        const format = result => {

            return result.data.list.map(i => ({
                live_id : 6,
                name : e(i.nick),
                room_name : e(i.introduction),
                room_id : i.privateHost,
                online : i.totalCount,
                id : 'huya_' + i.uid,
                url : `http://www.huya.com/${i.privateHost}`,
                cover : e_url(i.screenshot),
                avatar : e_url(i.avatar180),
                category_id : i.gid ,
                category_name : i.gameFullName,
                category_url : `http://www.huya.com/g/${i.gameHostName ? i.gameHostName : i.gid}`,
            }))
        }

        while (!page_count || page < page_count) {
            yield fetch(`${url}${page++}`, opt)
            .then(_=>_.json())
            .then(format)
        }
    },

    function *() {
        //繁星 url格式 http://apibj.fanxing.kugou.com/VServices/IndexService.IndexService.getLiveRoomListByType/${page}

        const url = "http://apibj.fanxing.kugou.com/VServices/IndexService.IndexService.getLiveRoomListByType/"
        let page = 1
        let done = false

        const format = result => {
            const list = result.data.list

            if (list.length === 0) return done = true

            return list.map( i => {
                const cate = i.starTagsList[0] == undefined ? {starTagsId: "20", starTagsName: "青春偶像"} : i.starTagsList[0]
                return { live_id : 7
                , name : e(i.nickName)
                , room_name : e(i.nickName)
                , online : i.viewerNum
                , id : 'fx_' + i.userId
                , room_id : i.roomId
                , url : `http://fanxing.kugou.com/${i.roomId}`
                , cover : e_url(i.imgPath)
                , avatar :  e_url(i.imgPath)
                , category_id : cate.starTagsId
                , category_name : cate.starTagsName
                , category_url : `http://fanxing.kugou.com/`
                }
            })
        }

        while ( ! done) {
            yield fetch (`${url}${page++}`, opt)
                .then(_=>_.text())
                .then( _=>_.slice(_.indexOf('{'), _.lastIndexOf('}') + 1) )
                .then(JSON.parse)
                .then(format)
        }

    },

    function *() {
        //来疯 url格式： http://www.laifeng.com/center?pageNo=${page}

        const url = `http://www.laifeng.com/center?pageNo=`;
        let page = 1
        const page_count = 11

        const format = result => {
            let $ = cheerio.load(result)
            let data = [];

            $('ul.user-list li:has(i.online)').map((i, t) => data.push(
                { live_id : 8
                , name : e($(t).find('p.name a').text())
                , room_name : e($(t).find('p.name a').text())
                , online : isNaN(parseInt($(t).find('p.data').text().split('\n')[2]))  ? 0 : parseInt($(t).find('p.data').text().split('\n')[2])
                , id : 'laifeng_' + $(t).find('p.name a').attr('href').replace(/[^\d]+/, '')
                , room_id : $(t).find('p.name a').attr('href').replace(/[^\d]+/, '')
                , url : $(t).find('p.name a').attr('href')
                , cover : $(t).find('p.pic img').attr('src')
                , avatar : $(t).find('p.pic img').attr('src')
                , category_id : 0
                , category_name : 0
                , category_url : `http://www.laifeng.com`
            }))

            return data
        }

        while( page_count > page ) {
            yield fetch (`${url}${page++}`, opt)
                .then(_=>_.text())
                .then(format)
        }
    },

    function *() {
        //花椒 url格式： http://www.huajiao.com/category/1000?pageno=${page}

        const url = `http://www.huajiao.com/category/1000?pageno=`;
        let page = 1
        const page_count = 3

        const format = result => {
            let $ = cheerio.load(result)
            let data = [];

            $('ul.g-list2 li.item').map((i, t) => data.push(
                { live_id : 9
                , name : e($(t).find('div.nickname').text())
                , room_name : e($(t).find('div.nickname').text())
                , online : isNaN(parseInt($(t).find('span.num').text()))  ? 0 : parseInt($(t).find('span.num').text())
                , id : 'haujiao_' + $(t).find('a').attr('href').replace(/[^\d]+/, '')
                , room_id : $(t).find('a').attr('href').replace(/[^\d]+/, '')
                , url : 'http://www.huajiao.com' + $(t).find('a').attr('href')
                , cover : $(t).find('div.pic img').attr('src')
                , avatar : $(t).find('div.pic img').attr('src')
                , category_id : 0
                , category_name : 0
                , category_url : `http://www.huajiao.com`
            }))

            return data
        }

        while( page_count > page ) {
            yield fetch (`${url}${page++}`, opt)
                .then(_=>_.text())
                .then(format)
        }
    }
]